package UDP;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private final String serverIP;
    private final int serverPort;

    public UdpEchoClient(String serverIP ,int serverPort) throws SocketException {//传入服务器IP和服务器端口
        this.socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }
    public void start() throws IOException {
        System.out.println("client start!");
        Scanner scanner = new Scanner(System.in);
        while (true){
            //1、用户从控制台输入
            System.out.print("请输入-> ");
            String request = scanner.next();
            if(request.equals("exit")){
                break;
            }
            //2、把用户输入的字符串构造成UDP数据报，发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(
                    request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(this.serverIP),this.serverPort);
            socket.send(requestPacket);
            //3、从服务器读取响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            //4、显示响应
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",6060);
        client.start();
    }
}
